# -*- encoding:utf-8 -*-
# @Time: 2022/10/26 21:15
# @Author : moran
# @Email: moran@maqu.com
# @File: serializers.py
# @Software: PyCharm
import re

from django.contrib.auth.models import User
from rest_framework.serializers import ModelSerializer
from rest_framework import serializers
from users.models import *


class UserDetailSerializer(ModelSerializer):
    class Meta:
        model = UserDetail
        exclude = ['is_delete']
        extra_kwargs = {
            'avatar': {'read_only': True},
            'user': {'required': False, 'write_only':True}
        }


class UserSerializer(ModelSerializer):
    userdetail = UserDetailSerializer(required=False, read_only=True)

    class Meta:
        model = User
        exclude = ['password','last_name']

    extra_kwargs = {
        'id': {'read_only': True},
        'last_login': {'read_only': True},
        'is_superuser': {'read_only': True},
        'is_staff': {'read_only': True},
        'is_active': {'read_only': True},
        'groups': {'read_only': True},
        'date_joined': {'read_only': True},
    }


class UpdatePasswordSerializer(serializers.Serializer):
    password = serializers.CharField(max_length=30, label='原密码')
    new_password = serializers.CharField(max_length=30, label='新密码')
    re_new_password = serializers.CharField(max_length=30, label='确认密码')

    def validate(self, attrs):
        if attrs['new_password'] != attrs['re_new_password']:
            raise serializers.ValidationError('两次密码输入不一致')
        return attrs


class AreaSerializer(ModelSerializer):
    """行政区划自身序列化器"""
    class Meta:
        model = Area
        fields = ['id', 'name']


class ParentSerializer(ModelSerializer):
    """行政区划自身序列化器及子级区划"""
    area_set = AreaSerializer(many=True, read_only=True)

    class Meta:
        model = Area
        fields = ['id', 'name', 'area_set']


class AddressSerializer(ModelSerializer):
    province_name = serializers.CharField(source='province.name', read_only=True)
    city_name = serializers.CharField(source='city.name', read_only=True)
    district_name = serializers.CharField(source='district.name', read_only=True)

    class Meta:
        model = Address
        exclude = ['is_delete']

    def validated_mobile(self, value):
        if not re.match(r'1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号码格式错误')
        return value

